package com.taiyuan.tongcheng.ui;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import org.json.JSONException;
import org.json.JSONObject;
import org.kymjs.kjframe.KJBitmap;
import org.kymjs.kjframe.KJHttp;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.http.HttpConfig;
import org.kymjs.kjframe.http.HttpParams;
import org.kymjs.kjframe.ui.BindView;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.KJLoger;
import org.kymjs.kjframe.utils.SystemTool;
import org.kymjs.kjframe.widget.RoundImageView;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.CountDownTimer;
import android.text.style.LineHeightSpan.WithDensity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.taiyuan.tongcheng.application.TCBroadcastAction;
import com.taiyuan.tongcheng.bean.CargoOrderSimple;
import com.taiyuan.tongcheng.bean.CargoPrice;
import com.taiyuan.tongcheng.bean.PushDriverInfo;
import com.taiyuan.tongcheng.config.TcConfig;
import com.taiyuan.tongcheng.http.HttpParamUtil;
import com.taiyuan.tongcheng.http.TcWebservice;
import com.taiyuan.tongcheng.http.WebData;
import com.taiyuan.tongcheng.jpush.TcJpushApi;
import com.taiyuan.tongcheng.jpush.TcPushReceiver;
import com.taiyuan.tongcheng.jsonparser.TcJsParser;
import com.taiyuan.tongcheng.util.ACache;
import com.taiyuan.tongcheng.util.L;
import com.tytc56.user.R;

/**
 * 
 * @Description 下单成功后的界面 ;
 * @author wzq
 * @date 2015-8-31 下午2:17:35
 * @update (date)
 * @version V1.0
 */
public class ExpressOrderIngActivity extends BaseActivityBtn {
	@BindView(id = R.id.btn_top_extral, click = true)
	private Button cancelOrderBtn;
	@BindView(id = R.id.tv_time_count_down)
	private TextView countDownTv;
	@BindView(id = R.id.rl_wait_reponse)
	private RelativeLayout waittingResRl;

	// 司机消息
	@BindView(id = R.id.ll_suc_reback)
	private LinearLayout driverLayout;
	@BindView(id = R.id.tv_driver_car_num)
	private TextView driverCarnoTv;
	@BindView(id = R.id.rl_driver_tel, click = true)
	private RelativeLayout telDriverBtn;
	@BindView(id = R.id.btn_goto_order_center, click = true)
	private Button orderCenterBtn;
	@BindView(id=R.id.tv_driver_lable)
	private TextView  driverInfoLable;
	@BindView(id=R.id.rataingBar_driver)
	private RatingBar  driverMarkBar;
//	@BindView(id=R.id.img_driver_icon)
//	private ImageView  driverIcon;
	@BindView(id=R.id.img_driver_head)
	private RoundImageView  driverHead;
	private PushDriverInfo driverInfo;
	private KJBitmap kjBitmap;

	// 倒计时所需字段
	private long totalTime = 90000;
	private long intervalTime = 1000;
	private CountDownTimer time;
	private int upNoRspCount=1;
	private int waitCount = 1;
	// IntentFiter
	private IntentFilter intentFilter;
	private CargoOrderSimple cargoSimple;
	private CargoPrice cargoPrice;

	// 定位相关
	@BindView(id = R.id.mapview_main)
	private MapView baiduMapView;
	private BaiduMap mapControl;
	private LocationClient mLocClient;
	private BitmapDescriptor mCurrentMarker;
	private MarkerOptions markerOptions;
	private GeoCoder geoCoder;
	BitmapDescriptor bitMapDes;

	//
	private int firstLoad = 0;

	@Override
	public void setRootView() {
		setContentView(R.layout.activity_express_ordering);
	}

	@Override
	public void widgetClick(View v) {
		super.widgetClick(v);
		switch (v.getId()) {
		case R.id.btn_top_extral:
			showinformDialog(getString(R.string.lable_ordering_titel),
					getString(R.string.lable_ordering_cancel),
					new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							tcInformDialog.dismiss();
							cancelOrder(spUtil.getCacheOrderId(), 1);
						}
					}, new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							tcInformDialog.cancel();
						}
					});
			break;
		case R.id.rl_driver_tel:
			Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"
					+ driverInfo.getDriverMobile()));
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
			break;
		case R.id.btn_goto_order_center:
			startActivity(OrderActivity.class);
			ExpressOrderIngActivity.this.finish();
			break;
		default:
			break;
		}
	}

	@Override
	public void initData() {
		super.initData();
		initView();
		totalTime=spUtil.getImExpireTime();
		upNoRspCount=spUtil.getWaitTimes();
		kjBitmap=new KJBitmap();
		cargoSimple = (CargoOrderSimple) ACache.get(getApplicationContext())
				.getAsObject("CARGO");
		// 价格信息
		cargoPrice = (CargoPrice) ACache.get(getApplicationContext())
				.getAsObject(ExpressActivity.TAG_ORDER_PRICE);
		initMap();
		registTcReiver();
		time = new CountDownTimer(totalTime, intervalTime) {

			@Override
			public void onTick(long millisUntilFinished) {
				long i = millisUntilFinished;
				i /= 1000;
				long minute = i / 60;
				long second = i % 60;
				countDownTv.setText(String.format("%02d:%02d", minute, second));
			}

			@Override
			public void onFinish() {
				firstLoad++;
				if (waitCount < upNoRspCount) {
					showinformDialog(getString(R.string.lable_ordering_titel),
							getString(R.string.lable_ordering_order_agin),
							new View.OnClickListener() {

								@Override
								public void onClick(View v) {
									tcInformDialog.dismiss();
									makeOrder();
									waitCount++;
								}
							}, new View.OnClickListener() {

								@Override
								public void onClick(View v) {
									tcInformDialog.dismiss();
								}
							});
				} else {
					showinformDialog(getString(R.string.lable_ordering_titel),
							getString(R.string.lable_ordering_order_busy),
							new View.OnClickListener() {

								@Override
								public void onClick(View v) {
									uploadNoResponse();
									tcInformDialog.dismiss();
								}
							}, new View.OnClickListener() {

								@Override
								public void onClick(View v) {
									tcInformDialog.dismiss();
									ExpressOrderIngActivity.this.finish();
								}
							});
				}
			}
		};

	}

	private void initMap() {
		// 初始化全局 bitmap 信息，不用时及时 recycle
		bitMapDes = BitmapDescriptorFactory.fromResource(R.drawable.map_pin);
		mapControl = baiduMapView.getMap();
		// 初始化搜索模块，注册事件监听
		geoCoder = GeoCoder.newInstance();
		baiduMapView.showScaleControl(false);
		baiduMapView.showZoomControls(false);
		MapStatus mMapStatus = new MapStatus.Builder()
				.target(new LatLng(cargoSimple.getStartLatitude(), cargoSimple
						.getStartLongitude())).zoom(17).build();
		// 定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
		MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory
				.newMapStatus(mMapStatus);
		// 改变地图状态
		mapControl.setMapStatus(mMapStatusUpdate);

		OverlayOptions oo = new MarkerOptions()
				.position(
						new LatLng(cargoSimple.getStartLatitude(), cargoSimple
								.getStartLongitude())).icon(bitMapDes)
				.zIndex(5);
		mapControl.addOverlay(oo);
		L.v("证书",
				SystemTool.getSign(getApplicationContext(), "com.tytc56.user"));
	}

	/**
	 * 
	 * @Description: 注册司机反馈广播
	 * @return void
	 * @throws
	 * @autour Administrator
	 * @date 2015-9-6 下午10:35:58
	 * @update (date)
	 */
	private void registTcReiver() {
		intentFilter = new IntentFilter();
		intentFilter.addAction(TcJpushApi.PUSH_REBACK_DRIVERINFO);
		registerReceiver(tcReceiver, intentFilter);
	}

	@Override
	public void initWidget() {
		super.initWidget();
		initView();
		topTv.setText(getString(R.string.lable_express_title_paiche));
		if (firstLoad == 0) {
			time.start();
			firstLoad++;
		}
	}

	/**
	 * 
	 * @Description: 上传无响应信息
	 * @return void
	 * @throws
	 * @autour wzq
	 * @date 2015-9-1 下午4:15:02
	 * @update (date)
	 */
	private void uploadNoResponse() {
		HttpConfig config = new HttpConfig();
		config.cacheTime = 0;
		KJHttp kjHttp = new KJHttp(config);
		HttpParams params = new HttpParams();
		params = HttpParamUtil.getNoResParams(ExpressOrderIngActivity.this,
				spUtil.getCacheOrderId());
		kjHttp.post(TcWebservice.WEBSERVER_IP
				+ TcWebservice.API.FREIGHT_ORDER_NO_RESPONSE, params,
				new HttpCallBack() {
					@Override
					public void onFailure(int errorNo, String strMsg) {
						super.onFailure(errorNo, strMsg);
					}

					@Override
					public void onSuccess(String t) {
						super.onSuccess(t);
						try {
							String rs = URLDecoder.decode(t, "UTF-8");
							KJLoger.debug(rs);
							WebData data = TcJsParser.getWedataData(rs);
							if (data.getStatus() == 1) {
								showConfirmDialog("温馨提示",
										"订单信息已提交到服务器，稍后会有客服跟你联系，请您耐心等待！",
										new View.OnClickListener() {

											@Override
											public void onClick(View arg0) {
												ExpressOrderIngActivity.this
														.finish();
											}
										});
							}

						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}
					}

				});
	}

	private BroadcastReceiver tcReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (TcJpushApi.PUSH_REBACK_DRIVERINFO.equals(intent.getAction())) {
				// 加震动
				
				waittingResRl.setVisibility(View.GONE);
				driverLayout.setVisibility(View.VISIBLE);
				String data = intent
						.getStringExtra(TcPushReceiver.TAG_PUSH_DRIVERINFO);
				driverInfo = (PushDriverInfo) JSON.parseObject(
						data, PushDriverInfo.class);
				KJLoger.debug(driverInfo.toString());
				driverCarnoTv.setText(driverInfo.getTruckNum());
				driverInfoLable.setText(TcConfig.DRIVER_LABLE_FRIST+driverInfo.getDriverName()+TcConfig.DRIVER_LABLE_END);
				driverMarkBar.setRating(Math.round(driverInfo.getPraisePercent())/20);
				time.cancel();
				if(driverInfo.getPic()!=null){
					kjBitmap.display(driverHead,driverInfo.getPic());
//					kjBitmap.displayCacheOrDefult(driverIcon,driverInfo.getPic(), R.drawable.driver_default_icon);
				}
				// 隐藏取消订单按钮
				rightBtn.setVisibility(View.GONE);
				topTv.setText("已派车");
			}

		}
	};

	/**
	 * @Description: 取消订单
	 * @return void
	 * @throws
	 * @autour wzq
	 * @date 2015-9-1 下午4:03:13
	 * @update (date)
	 */
	private void cancelOrder(String orderId, int reasonId) {
		HttpConfig config = new HttpConfig();
		config.cacheTime = 0;
		KJHttp kjHttp = new KJHttp(config);
		HttpParams params = new HttpParams();
		params = HttpParamUtil.getCancelImMsg(ExpressOrderIngActivity.this,
				reasonId, "", orderId);
		kjHttp.post(TcWebservice.WEBSERVER_IP
				+ TcWebservice.API.FREIGHT_ORDER_CANCLE_IM, params,
				new HttpCallBack() {
					@Override
					public void onFailure(int errorNo, String strMsg) {
						super.onFailure(errorNo, strMsg);
					}

					@Override
					public void onSuccess(String t) {
						try {
							String date = URLDecoder.decode(t, "UTF-8");
							KJLoger.debug(date);
							WebData webdata = TcJsParser.getWedataData(date);
							if (webdata.getStatus() == 1) {
								showCustomToast("取消订单成功");
								ExpressOrderIngActivity.this.finish();
							} else {
								showErroCustomToast("取消订单失败");
							}
							if (TcLoaddingDialog.isShowing()) {
								TcLoaddingDialog.cancel();
							}
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}
						super.onSuccess(t);
					}
				});
	}

	/**
	 * 
	 * @Description: 用户下单
	 * @return void
	 * @throws
	 * @autour wzq
	 * @date 2015-8-31 上午11:48:15
	 * @update (date)
	 */
	private void makeOrder() {
		HttpConfig config = new HttpConfig();
		config.cacheTime = 0;
		KJHttp kjh = new KJHttp(config);
		HttpParams params = new HttpParams();
		params = HttpParamUtil.getMakeExpressOrderParam(
				ExpressOrderIngActivity.this, cargoSimple, cargoPrice, spUtil);
		kjh.post(TcWebservice.WEBSERVER_IP
				+ TcWebservice.API.FREIGHT_MAKE_ORDER, params,
				new HttpCallBack() {
					@Override
					public void onSuccess(String t) {
						super.onSuccess(t);

						String str;
						try {
							str = URLDecoder.decode(new String(t), "UTF-8");
							KJLoger.debug(str);
							WebData webData = TcJsParser.getWedataData(str);
							if (webData.getStatus() == 1) {
								if (TcLoaddingDialog.isShowing()) {
									TcLoaddingDialog.dismiss();
								}
								JSONObject js;
								try {
									js = new JSONObject(webData.getData());
									String msgId = js.optString("returnId", "");
									spUtil.setCacheOrderId(msgId);
									int msgImFlag = js.optInt("isImFalg", 1);
									if (msgImFlag == 1) {
										time.start();
									}
								} catch (JSONException e) {
									e.printStackTrace();
								}

								showCustomToast(webData.getMsg());
							} else {
								showCustomToast(webData.getMsg());
							}
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int errorNo, String strMsg) {
						super.onFailure(errorNo, strMsg);
						if (errorNo == -1) {
							// 网络超时
							ViewInject.toast(strMsg);
						}
					}
				});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		time.cancel();
		unregisterReceiver(tcReceiver);
	}
}
